import LogFactory from "log/LogFactory";
const DB_NAME: "hyacinth" = "hyacinth";
const log = LogFactory.getLogger("DatabaseConnection");
/** 数据库连接获取类 */
export default class DatabaseConnection{
    private readonly database: Promise<IDBDatabase>;
    constructor() {
        // log.debug("数据库连接初始化");
        this.database = this.init();
    }
    private init(): Promise<IDBDatabase> {
        const request =indexedDB.open(DB_NAME, 1);
        // log.debug("创建数据库连接");
        return new Promise<IDBDatabase>((resolve, reject) => {
            request.onsuccess = (event: any) => {
                // log.debug("数据库连接成功");
                resolve(event.target.result);
            };
            request.onerror = (event) => {
                log.error("数据库连接失败");
                reject(event);
            };
            request.onupgradeneeded = (event: any) => {
                log.info("数据库升级");
                let db: IDBDatabase = event.target.result;
                db.createObjectStore("user-login-data", {keyPath: "username"});
                db.createObjectStore("user-config-data", {keyPath: "username"});
            };
        });
    }
    public async getConnection(): Promise<IDBDatabase>{
        return await this.database;
    }
    public async closeConnection(){
       let db = await this.database;
       db.close();
    }
}